<template>
  <div class="power-analysis-page">
    <!-- 页面导航 -->
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>
        <icon-menu-unfold />
      </a-breadcrumb-item>
      <a-breadcrumb-item>数据监测</a-breadcrumb-item>
      <a-breadcrumb-item>发电分析</a-breadcrumb-item>
    </a-breadcrumb>

    <!-- 搜索条件区域 -->
    <a-card>
      <a-space>
        <!-- 设备选择树 -->
        <a-tree-select
            v-model="selectTreeNode"
            :data="treeData"
            placeholder="请选择设备"
            style="width: 300px"
            :fieldNames="{
            key: 'deviceSn',
            title: 'deviceName',
            children: 'children'
          }"
            :allow-search="true"
            allow-clear
        />

        <!-- 时间选择组件 -->
        <timebar @change="timeBarChange" isCurrentDateDisabled />

        <!-- 查询按钮 -->
        <a-button type="primary" @click="search">查询</a-button>
      </a-space>
    </a-card>

    <!-- 图表展示区域 - 两行两列布局 -->
    <a-row style="margin-top: 10px" :gutter="12">
      <!-- 直流电流分析 -->
      <a-col :span="12">
        <a-card class="chart-container" :title="directChartInfo.cardName">
          <a-spin class="chart-view" :loading="loading">
            <CustomChart :options="directChartInfo.echartsOption" style="height: 300px" />
          </a-spin>
        </a-card>
      </a-col>

      <!-- 直流电压分析 -->
      <a-col :span="12">
        <a-card class="chart-container" :title="voltageChartInfo.cardName">
          <a-spin class="chart-view" :loading="loading">
            <CustomChart :options="voltageChartInfo.echartsOption" style="height: 300px" />
          </a-spin>
        </a-card>
      </a-col>
    </a-row>

    <a-row style="margin-top: 10px" :gutter="12">
      <!-- 交流电流分析 -->
      <a-col :span="12">
        <a-card class="chart-container" :title="exchangeChartInfo.cardName">
          <a-spin class="chart-view" :loading="loading">
            <CustomChart :options="exchangeChartInfo.echartsOption" style="height: 300px" />
          </a-spin>
        </a-card>
      </a-col>

      <!-- 交流电压分析 -->
      <a-col :span="12">
        <a-card class="chart-container" :title="acVoltageChartInfo.cardName">
          <a-spin class="chart-view" :loading="loading">
            <CustomChart :options="acVoltageChartInfo.echartsOption" style="height: 300px" />
          </a-spin>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { listFusionGroup } from '../../apis/datamonitor';
import { getChartInfo } from '../../apis/home-pv';
import timebar from '../../components/timebar/index.vue';
import useLoading from '../../utils/loading';
import CustomChart from '../../components/custom-chart/index.vue';
import { getTimeObject, handleConfigChart } from '../../utils/charts';

// 加载状态管理
const { loading, setLoading } = useLoading(true);

// 设备树数据和选中节点
const treeData = ref([]);
const selectTreeNode = ref('');

// 时间选项
const timeOptions = ref({});

// 图表信息接口定义
interface IChartInfo {
  cardName: string;
  echartsOption: any;
  singleInfo: null | any;
}

// 各类型图表信息
const directChartInfo = ref<IChartInfo>({
  cardName: '',
  echartsOption: {},
  singleInfo: null
});

const voltageChartInfo = ref<IChartInfo>({
  cardName: '',
  echartsOption: {},
  singleInfo: null
});

const exchangeChartInfo = ref<IChartInfo>({
  cardName: '',
  echartsOption: {},
  singleInfo: null
});

const acVoltageChartInfo = ref<IChartInfo>({
  cardName: '',
  echartsOption: {},
  singleInfo: null
});

// 获取设备树数据
const getTreeData = async () => {
  try {
    const res = await listFusionGroup({
      stationType: 2
    });
    if (res.data.code === 200) {
      // 处理树数据，设置不可选
      res.data.data.forEach((item: any) => {
        item.selectable = false;
      });
      treeData.value = res.data.data;
    }
  } catch (error) {
    console.error('获取设备数据失败:', error);
  }
};

// 设置默认选中节点
const setDefaultNode = () => {
  const treeNode = treeData.value;
  if (treeNode.length > 0) {
    const firstNode = treeNode[0];
    if (firstNode.children && firstNode.children.length > 0) {
      selectTreeNode.value = firstNode.children[0].deviceSn;
    }
  }
};

// 时间变化处理
const timeBarChange = (timer: any) => {
  timeOptions.value = timer;
  // 时间变化时重新获取数据
  search();
};

// 直流电流数据获取
const fetchDirectPowerData = async () => {
  try {
    setLoading(true);
    const params = {
      configId: '542',
      cardKey: '1719898937756',
      deviceSn: selectTreeNode.value,
      ...getTimeObject(timeOptions.value)
    };

    const res = await getChartInfo(params);
    if (res.data.code === 200) {
      directChartInfo.value = {
        ...res.data.data,
        echartsOption: handleConfigChart(res.data.data.echartsOption)
      };
    } else {
      directChartInfo.value = {
        cardName: '',
        echartsOption: {},
        singleInfo: null
      };
    }
  } catch (error) {
    console.error('获取直流电流数据失败:', error);
  } finally {
    setLoading(false);
  }
};

// 直流电压数据获取
const fetchVoltageData = async () => {
  try {
    setLoading(true);
    const params = {
      configId: '542',
      cardKey: '1719898940302',
      deviceSn: selectTreeNode.value,
      ...getTimeObject(timeOptions.value)
    };

    const res = await getChartInfo(params);
    if (res.data.code === 200) {
      voltageChartInfo.value = {
        ...res.data.data,
        echartsOption: handleConfigChart(res.data.data.echartsOption)
      };
    } else {
      voltageChartInfo.value = {
        cardName: '',
        echartsOption: {},
        singleInfo: null
      };
    }
  } catch (error) {
    console.error('获取直流电压数据失败:', error);
  } finally {
    setLoading(false);
  }
};

// 交流电流数据获取
const fetchExchangeData = async () => {
  try {
    setLoading(true);
    const params = {
      configId: '542',
      cardKey: '1719898941982',
      deviceSn: selectTreeNode.value,
      ...getTimeObject(timeOptions.value)
    };

    const res = await getChartInfo(params);
    if (res.data.code === 200) {
      exchangeChartInfo.value = {
        ...res.data.data,
        echartsOption: handleConfigChart(res.data.data.echartsOption)
      };
    } else {
      exchangeChartInfo.value = {
        cardName: '',
        echartsOption: {},
        singleInfo: null
      };
    }
  } catch (error) {
    console.error('获取交流电流数据失败:', error);
  } finally {
    setLoading(false);
  }
};

// 交流电压数据获取
const fetchACVoltageData = async () => {
  try {
    setLoading(true);
    const params = {
      configId: '542',
      cardKey: '1719898943387',
      deviceSn: selectTreeNode.value,
      ...getTimeObject(timeOptions.value)
    };

    const res = await getChartInfo(params);
    if (res.data.code === 200) {
      acVoltageChartInfo.value = {
        ...res.data.data,
        echartsOption: handleConfigChart(res.data.data.echartsOption)
      };
    } else {
      acVoltageChartInfo.value = {
        cardName: '',
        echartsOption: {},
        singleInfo: null
      };
    }
  } catch (error) {
    console.error('获取交流电压数据失败:', error);
  } finally {
    setLoading(false);
  }
};

// 查询按钮点击事件
const search = async () => {
  await fetchDirectPowerData();
  await fetchVoltageData();
  await fetchExchangeData();
  await fetchACVoltageData();
};

// 监听设备选择变化，重新获取数据
watch(selectTreeNode, () => {
  search();
});

// 组件挂载时初始化
onMounted(async () => {
  await getTreeData();
  setDefaultNode();
  await search();
});
</script>

<style scoped lang="less">
.power-analysis-page {
  .chart-container {
    height: 100%;
    width: 100%;

    :deep(.arco-card-body) {
      width: 100%;
      height: calc(100% - 46px);
    }

    .chart-view {
      width: 100%;
      height: 100%;
    }

    .arco-empty {
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }
  }
}
</style>